package com.xjx.service.impl;

import cn.hutool.extra.mail.Mail;
import cn.hutool.extra.mail.MailUtil;
import com.xjx.enmus.EmailStatus;
import com.xjx.service.EMailService;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.nio.charset.StandardCharsets;

@Slf4j
@Service
public class EMailServiceImpl implements EMailService {

    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public EmailStatus sendMail(String to, String subject, String content) {

        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true, StandardCharsets.UTF_8.name());
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            helper.setFrom("2968631987@qq.com");

            javaMailSender.send(message);
            log.info("邮件发送成功：收件人：{}", to);
            return EmailStatus.SUCCESS;
        } catch (Exception e) {
            log.error("邮件发送失败：收件人：{}，异常：{}", to, e.getMessage());
            return EmailStatus.FAILURE;
        }
    }

    @Override
    public EmailStatus sendMailWithAttachments(String to, String subject, String content, MultipartFile[] attachments) {
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true, StandardCharsets.UTF_8.name());

            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            helper.setFrom("2968631987@qq.com");

            // 遍历并添加多个附件
            if (attachments != null && attachments.length > 0) {
                for (MultipartFile attachment : attachments) {
                    if (!attachment.isEmpty()) {
                        helper.addAttachment(attachment.getOriginalFilename(), attachment);
                    }
                }
            }

            javaMailSender.send(message);
            log.info("带多个附件的邮件发送成功：收件人：{}", to);
            return EmailStatus.SUCCESS;
        } catch (Exception e) {
            log.error("带多个附件的邮件发送失败：收件人：{}，异常：{}", to, e.getMessage());
            return EmailStatus.FAILURE;
        }
    }
}
